//
//  OAuthViewController.swift
//  SinaWeibo23
//
//  Created by apple on 16/2/17.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    
    //属性的webView
    let webView = UIWebView()
    //MARK: 关闭视图控制器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func testAccount() {
        //本地代码 和  webView交互
        let jsString = "document.getElementById('userId').value = '1039448826@qq.com',document.getElementById('passwd').value = 'wang814'"
        //通过一个字符串对象来执行 javascript代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        view = webView
        //设置webView代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //手写代码 根视图的背景色默认是 透明的
//        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "testAccount")
        
        //使用webView加载授权页面
        loadOauthPage()
        
    }
    
    //在页面将要消失的时候 dismiss
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func loadOauthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        //获取url对象
        let url = NSURL(string: urlString)!
        //获取request对象
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
    }
}


//扩展 专门处理webView的协议方法
extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        //开启指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    //获取收取成功后的code(授权码)
    //shouldStartLoadWithRequest 每次加载新的页面 都会重新发起一个request
    //协议方法 返回值 为 bool类型 一般返回 true 提供协议的对象才能够正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            //urlString 为空 
            return false
        }
        
        //判断urlString中是否包含 code码
        if urlString.containsString("code") {
            //截取对应的code字符串 
            //query 获取url的参数的字段和对应值
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
//            printLog(urlString,query,code)
            //用code码换取 token(令牌)
//            loadAccessToken(code)
            
            AccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                //执行dismiss
                if isSuccess {
                    //登录成功
                    self.dismissViewControllerAnimated(true, completion: nil)
                    
                    //通知是同步还是异步的  同步的
                    //登录成功之后 将根视图控制器设置为 欢迎页面
                    NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: nil)
                    
                    printLog("come here oauth")
                } else {
                    //登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败,请检查网络")
                }
                
            })
            return false

        }
        return true
    }
}
